import React, { useRef } from 'react';
import { Button, Select, Space, Spin, Message } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';
import moment from 'moment';
import { connect } from 'umi';

import { UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components/index.js';
import { TjArrow, TjChart, TjDimension, TjTable, useTRState } from '@/pages/ETrade/components';
import { getTreeByCodes } from '@/utils/index.js';
import { useExcel } from '@/hooks';

import { default as HeadForm } from './form';
import { flexibleAggregation, queryMarketList, newFlexibleAggregation } from './services.js';
import {
  CODE1,
  getCharts,
  getTableData,
  tableColumns,
  removeEmptyRowData,
  exportDataConfig,
  OPTION_KEY,
} from './helper';
import styles from './index.less';
import { useThemeChange } from '@/hooks';
import { tileTbaleColumn, buildExportDataByTableData } from '@/utils/buildTableByDimension';
import { export_json_to_excel } from '@/utils/fileExport.js';

const orderDefault = ['交易单元', '日期', '时点'];
const orderOptions = ['交易单元', '日期', '时点'];
const exportKey = 'ProvinceSpotAnalysisExportButton';

const ProvinceSpotAnalysis = ({ menuCode, buttonPermissions }) => {
  /** data */
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 表单
    formValues: null,
    order: [...orderDefault], // 聚合维度（bind）
    filters: [], // 详情，已选维度值
    filterOptions: [], // 详情，维度选项
    // 数据
    loading: true,
    tableData: [],
    exportTable: [], // 导出数据
    charts: [],
    openLeft: false,
    openRight: false,
    sorts: [],
  });
  const { theme } = useThemeChange();
  const tileColumn = useRef();

  React.useEffect(() => {
    init();
  }, []);

  React.useEffect(() => {
    if (state.formValues && state.formValues.region) {
      setTimeout(() => {
        onChangeFilters(state.filters, state.formValues.region);
      }, 1);
    }
  }, [theme]);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryMarketList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { treeOptions } = getTreeByCodes(['market', 'group', 'station'], res.json);
      // tree需要唯一值键，处理一下
      power = treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
  };

  const fetch = async (values, reset) => {
    // 数据
    if (!values) return;
    const order = reset ? orderDefault : state.order;
    setState({
      formValues: values,
      loading: true,
    });
    const { region, dataTimeOrderType } = values;
    const params = {
      ...values,
      order,
    };
    let queryFn = () => flexibleAggregation(params);

    if (region === '21' || region === '23') {
      params.order = order?.map((v) => OPTION_KEY[v]);
      queryFn = () => newFlexibleAggregation(params);
    }

    const res = await queryFn();
    const { tableData, exportTable } = getTableData(res?.data, order, dataTimeOrderType, region);
    state.tableData = tableData;
    setState({ sorts: [] });
    // 聚合维度处理
    const filters = Array.from({ length: order.length - 1 }, () => 0);
    onChangeFilters(filters, region);
    setState({
      filters,
      tableData,
      exportTable,
      loading: false,
      order,
    });
  };

  /** methods */
  const onChangeForm = (values, reset) => {
    // 查询
    fetch(values, reset);
    tileColumn.current = tileTbaleColumn(tableColumns(values.region));
  };

  const onChangeFilters = (filters, region) => {
    // 聚合维度处理
    let tableData = state.tableData || [];
    let _options = [];
    const len = filters.length;
    const fn = (list, lv) => {
      const dataI = filters[lv];
      const { children = [] } = list[dataI] || {};
      if (lv === len) {
        _options[lv] = list;
      } else {
        _options[lv] = list.map((x, idx) => ({ label: x[CODE1], value: idx }));
      }
      lv < len && fn(children, lv + 1);
    };
    // 去掉总合计
    fn(tableData.slice(1), 0);
    // 拿到选项和渲染结果
    const filterOptions = _options.slice(0, -1);
    const chartData = _options?.[_options.length - 1];
    const charts = getCharts(chartData, region);
    setState({
      charts,
      filterOptions,
    });
  };

  const onChangeFilterItem = (lv, idx) => {
    // 当前维度索引更新，子维度索引清0
    let { filters } = state;
    const arrBefore = filters.slice(0, lv + 1);
    const arrAfter = filters.slice(lv + 1).map(() => 0);
    filters = [...arrBefore, ...arrAfter];
    filters[lv] = idx;
    setState({ filters });
    onChangeFilters(filters, state.formValues.region);
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return Message.info('请联系管理员获取相关权限');
    const { startDate, endDate, region } = state.formValues;
    const sta = moment(startDate).format('YYYYMMDD');
    const end = moment(endDate).format('YYYYMMDD');
    const data = buildExportDataByTableData(state.tableData, tileColumn.current);

    const { multiHeader, header, exportMerges } = exportDataConfig(region);
    const params = {
      multiHeader: multiHeader,
      header: header,
      data: data,
      merges: exportMerges,
      filename: `省间现货复盘分析-${sta}_${end}`,
    };
    export_json_to_excel(params);

    // useExcel({
    //   filename: `省间现货复盘分析-${sta}_${end}`,
    //   columns: tableColumns(region),
    //   data: state.exportTable,
    //   merges: [CODE1],
    // });
  };

  /** render */
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: state.tableData, columns: tableColumns(state?.formValues?.region) })
    .primaryKey('id')
    .use(features.treeMode({ iconIndent: 5 }))
    .use(
      features.sort({
        mode: 'single',
        sorts: state.sorts,
        keepDataSource: true,
        onChangeSorts: (params) => {
          setState({ sorts: params });
          if (params.length) {
            const _dataSource = _.cloneDeep(state.tableData);
            const total = _dataSource[0];
            const spliceData = _dataSource.splice(1);
            const { sortData, noSortData } = removeEmptyRowData(spliceData, params[0].code);

            let newDataSource = [];
            newDataSource = sortData.sort((a, b) => {
              return params[0].order === 'desc'
                ? b[params[0].code] - a[params[0].code]
                : a[params[0].code] - b[params[0].code];
            });

            setState({ tableData: [total, ...newDataSource, ...noSortData] });
            return;
          }

          setState({ tableData: state.tableData });
        },
        highlightColumnWhenActive: true,
      }),
    );

  const _renderContent = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return (
      <div className={styles.flex}>
        {/* 左表 */}
        <div
          className={styles.box}
          style={{ width: state.openLeft ? '100%' : state.openRight ? 0 : '50%' }}
        >
          <TjArrow
            value={state.openLeft}
            position="right"
            onChange={(openLeft) => setState({ openLeft })}
          />
          <div className={styles.boxInner}>
            <div>
              <div className={styles.inhead}>
                <TjDimension
                  value={state.order}
                  options={orderOptions}
                  onChange={(order) => setState({ order })}
                  onPoly={() => fetch(state.formValues)}
                />
              </div>
              <div className={styles.inbody}>
                <TjTable {...pipeline.getProps()} useVirtual={false} />
              </div>
            </div>
          </div>
        </div>
        {/* 右图 */}
        <div
          className={styles.box}
          style={{ width: state.openRight ? '100%' : state.openLeft ? 0 : '50%' }}
        >
          <TjArrow
            value={state.openRight}
            position="left"
            onChange={(openRight) => setState({ openRight })}
          />
          <div className={styles.boxInner}>
            <div>
              <div className={styles.inhead}>
                <Space size={16}>
                  {state.filterOptions.map((options, lv) => (
                    <Select
                      key={lv}
                      style={{ minWidth: 140 }}
                      value={state.filters[lv]}
                      options={options}
                      optionFilterProp="label"
                      onChange={(idx) => onChangeFilterItem(lv, idx)}
                      showSearch
                    />
                  ))}
                </Space>
              </div>
              <div className={styles.inbody}>
                <div className={styles.chartTitle}>
                  盈亏差额
                  <span className={styles.unit}>单位：元</span>
                </div>
                <div className={styles.chart}>
                  <TjChart option={state.charts?.[0]} group={menuCode} />
                </div>
                <div className={styles.chartTitle}>
                  电价对比
                  <span className={styles.unit}>单位：元/MWh</span>
                </div>
                <div className={styles.chart}>
                  <TjChart option={state.charts?.[1]} group={menuCode} />
                </div>
                <div className={styles.chartTitle}>
                  省间成交电量
                  <span className={styles.unit}>单位：MWh</span>
                </div>
                <div className={styles.chart}>
                  <TjChart option={state.charts?.[2]} group={menuCode} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.container}>
        <div className={styles.head}>
          <HeadForm power={state.power} onChange={onChangeForm} />
          <div style={{ marginLeft: '16px' }}>
            <Button
              disabled={!state.tableData?.length}
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </div>
        </div>
        <div className={styles.main}>{_renderContent()}</div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(ProvinceSpotAnalysis);
